package com.example.component;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

public class CheckableListView extends ListView {

	public CheckableListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public CheckableListView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CheckableListView(Context context) {
		super(context);
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(new CheckableAdatper(adapter));
	}

	@Override
	public void setChoiceMode(int choiceMode) {
		super.setChoiceMode(choiceMode);
		if (choiceMode == AbsListView.CHOICE_MODE_NONE) {
			clearChoices();
		}
		CheckableAdatper adpater = (CheckableAdatper) getAdapter();
		if (adpater != null) {
			adpater.notifyDataSetChanged();
		}
	}

	class CheckableAdatper extends BaseAdapter {
		private ListAdapter mAdapter;

		private CheckableAdatper(ListAdapter adapter) {
			mAdapter = adapter;
		}

		public void setCheckable(boolean checkable) {
		}

		@Override
		public int getCount() {
			return mAdapter.getCount();
		}

		@Override
		public Object getItem(int position) {
			return mAdapter.getItem(position);
		}

		@Override
		public long getItemId(int position) {
			return mAdapter.getItemId(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CheckableLinearLayout view = (CheckableLinearLayout) mAdapter.getView(position, convertView, parent);
			if (view == null) {
				throw new RuntimeException(
						"Your content must have a CheckableLinearLayout.");
			}
			if (getChoiceMode() == AbsListView.CHOICE_MODE_NONE) {
				view.showCheckBox(false);
			} else {
				view.showCheckBox(true);
			}
			return view;
		}
	}
}
